const path = require('path');
const fs = require('fs-extra');
const express = require('express');
const multer = require('multer');
const { analyzeFilePurpose } = require('../ai');
const { getImageManifest } = require('../manifest');

const router = express.Router();
const upload = multer({ storage: multer.memoryStorage() });

router.post('/analyze-file-purpose', upload.none(), async (req, res) => {
    console.log('analyze file purpose');
    const uuid = req.body.uuid;
    if (!uuid) {
        res.json({ code: 400, message: 'uuid不能为空' });
        return;
    }
    const zipFileHash = req.body.zipFileHash;
    if (!zipFileHash) {
        res.json({ code: 400, message: 'zipFileHash不能为空' });
        return;
    }
    const pdfFileHash = req.body.pdfFileHash;
    if (!pdfFileHash) {
        res.json({ code: 400, message: 'pdfFileHash不能为空' });
        return;
    }
    const imageFileName = req.body.imageFileName;
    if (!imageFileName) {
        res.json({ code: 400, message: '图片文件名不能为空' });
        return;
    }
    const unzipDir = path.join(global.__rootDir, 'uploads', uuid, zipFileHash);
    const pdfFileDir = path.join(unzipDir, pdfFileHash);
    const purposeResultPath = path.join(pdfFileDir, 'purpose.json');
    if (fs.existsSync(purposeResultPath)) {
        const result = await fs.readJson(purposeResultPath);
        return res.json({ code: 200, message: '分析成功', result: result });
    }
    let manifest = getImageManifest({zipFileHash, pdfFileHash, uuid});
    const imageInfo = manifest.imageList.find(
        (e) => e.imageName === imageFileName
    );
    console.log('分析功能: ' + imageInfo.imageName);
    const result = await analyzeFilePurpose({
        imageFileId: imageInfo.fileId,
    });
    if (!result) {
        res.json({ code: 500, message: '分析失败' });
        return;
    }
    fs.writeFileSync(purposeResultPath, JSON.stringify(result, null, 4), {
        encoding: 'utf-8',
    });
    res.json({ code: 200, message: '分析成功', result: result });
});

module.exports = router;
